package zhh.tangbao.commodity.serivce.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import zhh.tangbao.auxiliary.service.SystemFileService;
import zhh.tangbao.commodity.dao.CommodityEntityDao;
import zhh.tangbao.commodity.dao.CommodityMachineStockDao;
import zhh.tangbao.commodity.dto.CommodityEntityQueryDto;
import zhh.tangbao.commodity.entity.CommodityEntity;
import zhh.tangbao.commodity.entity.CommodityMachineStock;
import zhh.tangbao.commodity.serivce.CommodityEntityService;
import zhh.tangbao.commodity.vo.CommodityEntityVo;
import zhh.tangbao.system.constant.DataStatus;
import zhh.tangbao.commodity.constant.SellStatus;
import zhh.tangbao.system.dto.BaseEntityUpdateDto;
import zhh.tangbao.system.exception.ServiceException;
import zhh.tangbao.system.utils.UserHolderUtil;
import zhh.tangbao.user.dao.UserDao;
import zhh.tangbao.user.vo.UserAccountAndNameVo;
import zhh.tangbao.user.vo.UserVo;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 2023/2/28
 * @author 粥灰灰
 * @version 1.0
 * 描述
 */

@Service
public class CommodityEntityServiceImpl implements CommodityEntityService {

    @Autowired
    private CommodityEntityDao commodityEntityDao;

    @Autowired
    private CommodityMachineStockDao commodityMachineStockDao;

    @Autowired
    private UserHolderUtil userHolderUtil;

    @Autowired
    private SystemFileService systemFileService;

    @Autowired
    private UserDao userDao;

    @Override
    public Page<CommodityEntity> page(CommodityEntityQueryDto dto) {
        Page<CommodityEntity> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        QueryWrapper<CommodityEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("record_time");
        queryWrapper.eq("data_status", DataStatus.ENABLE);
        if (StrUtil.isNotBlank(dto.getCommodityName())) {
            queryWrapper.like("commodity_name", dto.getCommodityName());
        }
        if (null != dto.getCommodityPriceLow() && null != dto.getCommodityPriceHeight()) {
            queryWrapper.between("commodity_price", dto.getCommodityPriceLow(), dto.getCommodityPriceHeight());
        }
        if (StrUtil.isNotBlank(dto.getId())) {
            queryWrapper.eq("id", dto.getId());
        }
        if (null != dto.getSellStatus()) {
            queryWrapper.eq("sell_status", dto.getSellStatus());
        }
        return commodityEntityDao.selectPage(page, queryWrapper);
    }

    @Override
    public int add(CommodityEntity commodityEntity, Long imgFileId) {
        UserVo currentUser = userHolderUtil.getCurrentUser();
        commodityEntity.setBaseCreateInfo(currentUser.getId(), DataStatus.ENABLE);
        int i = commodityEntityDao.insert(commodityEntity);
        // 因为commodity对象引用在add中没变，所以可以直接用于取ID
        if (null != imgFileId) {
            // 访问路径绑定完成后再把商品实体ID绑定到文件记录中
            // 如果有附件则需要绑定附件
            int bindingFile = systemFileService.bindingFile(commodityEntity.getId(), imgFileId);
            if (bindingFile <= 0) {
                throw new ServiceException("文件绑定失败");
            }
        }
        return i;
    }

    @Override
    public int delete(String id) {
        UserVo currentUser = userHolderUtil.getCurrentUser();
        CommodityEntity commodityEntity = commodityEntityDao.selectOne(new QueryWrapper<CommodityEntity>().eq("id", id).eq("data_status", DataStatus.ENABLE));
        Assert.notNull(commodityEntity, "该商品实体不存在或已被删除");
        commodityEntity.setUpdateInfo(currentUser.getId())
                .setDataStatus(DataStatus.DELETED);
        return commodityEntityDao.updateById(commodityEntity);
    }

    @Override
    public int update(CommodityEntity commodityEntity) {
        UserVo currentUser = userHolderUtil.getCurrentUser();
        commodityEntity.setUpdateInfo(currentUser.getId());
        return commodityEntityDao.updateById(commodityEntity);
    }

    @Override
    public CommodityEntityVo get(String id) {
        CommodityEntity commodityEntity = commodityEntityDao.selectOne(new QueryWrapper<CommodityEntity>().eq("id", id).eq("data_status", DataStatus.ENABLE));
        Assert.notNull(commodityEntity, "该商品实体不存在或被删除");
        List<String> userIds = Lists.newArrayList(commodityEntity.getRecordUserId(), commodityEntity.getUpdateUserId()).stream().filter(StrUtil::isNotEmpty).collect(Collectors.toList());
        List<UserAccountAndNameVo> userAccountAndNameById = userDao.getUserAccountAndNameById(userIds);
        if (CollUtil.isEmpty(userAccountAndNameById)) {
            return new CommodityEntityVo(commodityEntity);
        }
        Map<String, UserAccountAndNameVo> idMap = userAccountAndNameById.stream().collect(Collectors.toMap(UserAccountAndNameVo::getId, Function.identity()));
        return new CommodityEntityVo(commodityEntity, idMap.get(commodityEntity.getRecordUserId()), idMap.get(commodityEntity.getUpdateUserId()));
    }

    @Override
    public int takeOffTheSell(String commodityEntityId) {
        CommodityEntity commodityEntity = commodityEntityDao.selectOne(new QueryWrapper<CommodityEntity>().eq("id", commodityEntityId).eq("data_status", DataStatus.ENABLE));
        Assert.notNull(commodityEntity, "该商品实体不存在或被删除");
        Date now = new Date();
        String currentUserId = userHolderUtil.getCurrentUser().getId();
        commodityEntity.setSellStatus(SellStatus.TAKE_OFF)
                .setUpdateInfo(currentUserId, now);
        return commodityEntityDao.updateById(commodityEntity);
    }

    @Override
    public int takeOnTheSell(String commodityEntityId) {
        CommodityEntity commodityEntity = commodityEntityDao.selectOne(new QueryWrapper<CommodityEntity>().eq("id", commodityEntityId).eq("data_status", DataStatus.ENABLE));
        Assert.notNull(commodityEntity, "该商品实体不存在或被删除");
        String currentUserId = userHolderUtil.getCurrentUser().getId();
        commodityEntity.setSellStatus(SellStatus.TAKE_ON)
                .setUpdateInfo(currentUserId, new Date());
        return commodityEntityDao.updateById(commodityEntity);
    }

    @Override
    public int isUsing(String commodityEntityId) {
        Integer count = commodityMachineStockDao.selectCount(
                new QueryWrapper<CommodityMachineStock>()
                        .eq("commodity_entity_id", commodityEntityId)
                        .eq("data_status", DataStatus.ENABLE)
        );
        return count;
    }

    @Override
    public int batchChangeSellStatus(List<String> ids, int sellStatus) {
        String currentUserId = userHolderUtil.getCurrentUser().getId();
        return commodityEntityDao.batchUpdateSellStatus(ids, sellStatus, new BaseEntityUpdateDto(currentUserId, new Date()));
    }

    @Transactional
    @Override
    public int batchDelete(List<String> ids) {
        String currentUserId = userHolderUtil.getCurrentUser().getId();
        commodityMachineStockDao.batchDeleteByCommodityEntityId(ids, new BaseEntityUpdateDto(currentUserId, new Date(), DataStatus.DELETED));
        return commodityEntityDao.batchDelete(ids, new BaseEntityUpdateDto(currentUserId, new Date(), DataStatus.DELETED));
    }

}
